package com.example.whitespace.annotation;

import com.example.whitespace.enums.ParameterType;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

@Aspect
@Component
public class TrimWhitespaceAspect {

    @Pointcut("@annotation(com.example.whitespace.annotation.TrimWhitespace)")
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取方法上的注解
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        TrimWhitespace annotation = method.getAnnotation(TrimWhitespace.class);
        // 获取type类型
        ParameterType type = annotation.type();
        Object[] args = joinPoint.getArgs();
        for (int i = 0; i < args.length; i++) {
            if(ParameterType.CLASS.equals(type)){
                Class<?> objClass = args[i].getClass();
                Field[] fields = objClass.getDeclaredFields();
                for (Field field : fields) {
                    field.setAccessible(true);
                    if (field.getType().equals(String.class)) {
                        String value = (String) field.get(args[i]);
                        if (value != null) {
                            String trimmedValue = value.trim().replaceAll(" ","");
                            field.set(args[i], trimmedValue);
                        }
                    }
                }
            }else if(ParameterType.STRING.equals(type)){
                args[i] = ((String) args[i]).trim().replaceAll(" ","");
            }
        }
        return joinPoint.proceed(args);
    }

}
